﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EDTS.Model.Weixin;
using EDTS.Weixin.Submits;
namespace EDTS.Data.Weixin
{
    public class WxAppCommand
    {
        public static WxAppModel GetModel(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.WxApps.FirstOrDefault(p => p.Guid == guid);
                    if (d != null)
                    {
                        var ret = Convertor.ConvertTo<WxAppModel, WxApp>(d);
                        return ret;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 更新访问令牌
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="token"></param>
        /// <param name="exptime"></param>
        public static string UpdateAccessToken(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.WxApps.FirstOrDefault(p => p.Guid == guid);
                    if (d != null)
                    {
                        if (d.AccessExpired == null || d.AccessExpired.Value.CompareTo(DateTime.Now) < 0)
                        {
                            var token = Submit.GetAccessToken(d.CorpID, d.Secret);
                            d.AccessToken = token;
                            d.AccessExpired = DateTime.Now.AddHours(1);
                            db.DataContext.SaveChanges();
                        }
                        return d.AccessToken;
                    }
                }
            }
            throw new Utils.IException("无效的WxApp Guid.");
        }
        public static string UpdateAccessToken(int id)
        {
            if (id>0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.WxApps.FirstOrDefault(p => p.ID==id);
                    if (d != null)
                    {
                        if (d.AccessExpired == null || d.AccessExpired.Value.CompareTo(DateTime.Now) < 0)
                        {
                            var token = Submit.GetAccessToken(d.CorpID, d.Secret);
                            d.AccessToken = token;
                            d.AccessExpired = DateTime.Now.AddHours(1);
                            db.DataContext.SaveChanges();
                        }
                        return d.AccessToken;
                    }
                }
            }
            throw new Utils.IException("无效的WxApp ID.");
        }
    }
}
